package com.myres.struts.action;
import org.apache.struts.action.ActionServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Cookie;

import com.myres.model.Order;
import com.myres.model.User;
import com.myres.log.db.LogService;
import com.myres.util.RequestLog;
import com.myres.util.ScoreTool;
import com.myres.message.actions.MessageService;
import com.myres.orders.db.OrderService;

public class MyActionServlet extends ActionServlet{
	protected void process(HttpServletRequest request,HttpServletResponse response)
	    throws java.io.IOException,javax.servlet.ServletException{
		request.setCharacterEncoding("utf-8");
		//response.setCharacterEncoding("GBK");
		processCookie(request, response);
		super.process(request, response);  
	}
	private void processCookie(HttpServletRequest request,HttpServletResponse response){
		User user=(User)request.getSession().getAttribute("user");
		if(user!=null){
			//ScoreTool.sendScore(user.getId());
			//RequestLog.logRequest(request);
			getUserNewMessageCount(request, user);
			getUserLatestOrder(request,user);
			return;
		}
		Cookie[] cookies=request.getCookies();
		    if(cookies==null) return;
		    for(Cookie cookie:cookies){
		    	
		    	String name=cookie.getName();
		    	if(!name.equals("yipinzhouba_uid")) continue;
		    	String uid=cookie.getValue();
		    	user=new LogService().selectUser(Integer.parseInt(uid));
		    	if(user==null) return; 
		    	System.out.println("Read Cookie "+user.getScore()+"fen ");
		    	//ScoreTool.sendScore(user.getId());
		    	//RequestLog.logRequest(request);
		    	request.getSession().setAttribute("user", user);
		    	getUserNewMessageCount(request, user);
		    	break;
		    	}	
	    }
	private void getUserNewMessageCount(HttpServletRequest request,User user){
		int newMessageCount=new MessageService().getNewMessageCount(user.getId());
		if(newMessageCount>0)request.setAttribute("newmessagecount", newMessageCount);
	}
	private void getUserLatestOrder(HttpServletRequest request,User user){
		Order order=new OrderService().getLatestOrderOfUser(user.getId());
		request.getSession().setAttribute("latest_order", order);
		
		
	}
}
